let parentCategoryJson
let childCategoryJson

$(document).ready(function () {
    //获取父菜单列表
    getParentItemList();
    getCategoryInfo();

});
//数据表格
layui.use(['table','upload','form'], function() {
    let table = layui.table
        ,form = layui.form
        ,upload = layui.upload;
    form.render();

    form.on('submit(editItem)',function () {
        editItem();
    });


    //表格渲染
    table.render({
        elem: '#itemList'
        ,method:"post"
        , url: '/itemList'
        , toolbar: '#topTools' //开启头部工具栏，并为其绑定左侧模板
        , title: '商品列表'
        ,totalRow: true
        ,request:{
            pageName: 'curPage',
            limitName:'pageSize'
        },parseData:function (res) {
            return {
                "code": res.code==200? 0 : -1,
                "msg": "",
                "count":res.data.count,
                "data":res.data.data
            }
        }
        , cols: [
            [
                {field: 'id', title: 'ID', width: 60, fixed: 'left', unresize: true, sort: true,totalRowText: '合计'}
                , {field: 'itemName', title: '商品名',width:100}
                , {field: 'rootCatId', title: '父分类',width:100}
                , {field: 'catId', title: '子分类',width:100}
                , {field: 'sellCounts', title: '销量',width:100}
                , {field: 'stock', title: '库存',width:100}
                , {field: 'onOffStatus', title: '状态',width:100,templet:"<div>{{(d.onOffStatus == 1)?'上架':(d.onOffStatus == 2)?'下架':'优选审核中'}}</div>"}
                , {field: 'createTime', title: '创建日期',width:100,templet:"<div>{{layui.util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss')}}</div>"}
                , {field: 'priceNormal', title: '原价',width:100,templet:function (data) {
                    let price = parseFloat(data.priceNormal).toFixed(2);
                    return price;}}
                , {field: 'discount', title: '折扣力度',width:100}
                , {field: 'priceDiscount', title: '折扣价',width:100,templet:function (data) {
                    let price = parseFloat(data.priceDiscount).toFixed(2);
                    return price;}}
                , {field: 'isSpecial', title: '是否为优选商品',width:100}
                , {fixed: 'right', title: '操作', toolbar: '#itemOperator',width:200}
            ]]
        , page: true
        ,done:function (res,curr,count) {

            $("[data-field='rootCatId']").children().each(function () {
                let rootCatId = $(this).text();
                $(this).text(parentCategoryJson[rootCatId])

            })
            $("[data-field='catId']").children().each(function () {
                let catId = $(this).text();
                $(this).text(childCategoryJson[catId])

            });
            getParentCategoryList();

        }
    });


    function selectItem(){
        let key = $("#searchItemName").val();
        let catId = $("#childCategorySelect").val();
        let rootCatId = $("#parentCategorySelect").val();
        table.reload('itemList',{
            method: 'post'
            ,where:{
                'itemName':key,
                'catId':catId,
                'rootCatId':rootCatId
            }
            ,page: {
                curr:1
            }
            ,done:function () {
                $("[data-field='rootCatId']").children().each(function () {
                    let rootCatId = $(this).text();
                    $(this).text(parentCategoryJson[rootCatId])

                })
                $("[data-field='catId']").children().each(function () {
                    let catId = $(this).text();
                    $(this).text(childCategoryJson[catId])
                });
               selectTargetKeep(rootCatId,catId);
                form.val("itemSearchForm",{
                    "searchItemName":key,
                });

                form.render('select');
                $("#searchItemName").val(key);
            }

        });




    }
    //监听头部工具事件
    table.on('toolbar(itemList)',function (obj) {
        switch (obj.event) {
            case 'addItem' :
                editItemModel();
                break;
            case 'searchItem':
                selectItem();
                break;
            case 'reloadTable':
                reloadTable();
                break;
        }



    });
    function reloadTable() {
        let key = $("#searchItemName").val();
        let catId = $("#childCategorySelect").val();
        let rootCatId = $("#parentCategorySelect").val();
        let currentPage=$(".layui-laypage-em").next().html();
        table.reload('itemList',{
            method: 'post'
            ,where:{
                'itemName':key,
                'catId':catId,
                'rootCatId':rootCatId
            }
            ,page: {
                curr:currentPage
            }
            ,done:function () {
                $("[data-field='rootCatId']").children().each(function () {
                    let rootCatId = $(this).text();
                    $(this).text(parentCategoryJson[rootCatId]);
                })
                $("[data-field='catId']").children().each(function () {
                    let catId = $(this).text();
                    $(this).text(childCategoryJson[catId])
                });
                selectTargetKeep(rootCatId,catId);
                form.val("itemSearchForm",{
                    "searchItemName":key,
                });

                form.render('select');
                $("#searchItemName").val(key);
            }

        });
    }

    //监听行工具事件
    table.on('tool(itemList)', function(obj){
        let data = obj.data;
        if(obj.event === 'isSpecial'){
            layer.confirm('是否确认商品通过优选审核？', function(index){
                $.ajax({
                    url:"/enableItem",
                    method:"post",
                    charset:"UTF-8",
                    dataType:"json",
                    contentType:"application/json;charset=utf-8;",
                    data:JSON.stringify(data),
                    success:function (data) {
                        if (data == "1"){
                            alert("特选商品上架成功");
                            reloadTable();
                            layer.close(layer.index);
                        }else {
                            alert("特选商品上架失败");
                            layer.close(layer.index);
                        }
                    }
                });

                layer.close(index);
            });
        }else if(obj.event === "edit"){
            editItemModel(data);
        }else if(obj.event=== "enable"){
            $.ajax({
                url:"/enableItem",
                method:"post",
                charset:"UTF-8",
                dataType:"json",
                contentType:"application/json;charset=utf-8;",
                data:JSON.stringify(data),
                success:function (data) {
                    if (data == "1"){
                        alert("上架成功");
                        reloadTable();
                        layer.close(layer.index);
                    }else {
                        alert("上架失败");
                        layer.close(layer.index);
                    }
                }
            });
        }else if(obj.event==="disable"){
            $.ajax({
                url:"/disableItem",
                method:"post",
                charset:"UTF-8",
                dataType:"json",
                contentType:"application/json;charset=utf-8;",
                data:JSON.stringify(data),
                success:function (data) {
                    if (data == "1"){
                        alert("下架成功");
                        reloadTable();
                        layer.close(layer.index);
                    }else {
                        alert("下架失败");
                        layer.close(layer.index);
                    }
                }
            });
        }else if(obj.event == "reloadTable"){
            reloadTable();
        }
    });
    //监听select
    form.on('select(parentItem)',function (data) {
        let parentId = data.value;
        getChildItemList(parentId,form);
        form.render('select');
    });
    //监听select（搜索框）
    form.on('select(parentCategory)',function (data) {
        let parentId = data.value;
        // console.log("parentId="+parentId)
        getChildCategoryList(parentId);
        if (parentId !=""){
            $("#selectChildCategory").removeClass("layui-hide");
        }else {
            $("#selectChildCategory").addClass("layui-hide");
        }

        form.render();
    });
    function getParentCategoryList() {
        $.ajax({
            url: "/getParentCategory",
            method: "post",
            charset: "UTF-8",
            async: true,
            success: function (res) {
                let parentCategorySelect = $("#parentCategorySelect");
                parentCategorySelect.empty();
                parentCategorySelect.append("<option name='parentCategory' value=" + "" + ">" + "请选择分类" + "</option>");
                let parentCategoryList = res.data;
                $.each(parentCategoryList, function (index, value) {
                    parentCategorySelect.append("<option name='parentCategory' value='" + value.id + "'" + ">" + value.name + "</option>");
                });
                form.render('select');
                // getChildCategoryList($("#parentCategorySelect").val());
            }

        });
    }

    function getParentCategoryListSelect(rootCatId) {
        $.ajax({
            url: "/getParentCategory",
            method: "post",
            charset: "UTF-8",
            async: true,
            success: function (res) {
                let parentCategorySelect = $("#parentCategorySelect");
                parentCategorySelect.empty();
                parentCategorySelect.append("<option name='parentCategory' value=" +""+">" + "请选择分类" + "</option>");
                let parentCategoryList = res.data;
                $.each(parentCategoryList, function (index, value) {
                    parentCategorySelect.append("<option name='parentCategory' value='" + value.id + "'" + ">" + value.name + "</option>");
                });
                $("#selectParentCategory option").each(function () {
                    if ($(this).attr("value") == rootCatId){
                        $(this).prop("selected",'selected');
                    }
                });
                form.render('select');
            }

        });
    }

    function getChildCategoryList(parentId) {
        $.ajax({
            url: "/getChildCategory",
            method: "post",
            charset: "UTF-8",
            data: "parentId=" + parentId,
            async: false,
            success: function (res) {
                let childCategorySelect = $("#childCategorySelect");
                childCategorySelect.empty();
                let chileCategoryList = res.data;
                childCategorySelect.append("<option name='childCategory' value=''" +"'"+ ">" + "请选择分类" + "</option>");
                if (parentId != "") {
                    $.each(chileCategoryList, function (index, value) {
                        childCategorySelect.append("<option name='childCategory' value='" + value.id + "'" + ">" + value.name + "</option>");
                    });
                }
                form.render('select');
            }

        })
    }
    function selectTargetKeep(rootCatId,catId) {
        getParentCategoryListSelect(rootCatId);
        getChildCategoryList(rootCatId);
        form.render('select')
        if (rootCatId != '' || rootCatId != undefined || rootCatId != null){
            $("#selectChildCategory").removeClass("layui-hide");
        }

        $("#selectChildCategory option").each(function () {
            if ($(this).attr("value") == catId){
                $(this).prop("selected",'selected');
            }
        });



        form.render('select');
    }

    //图片上传
    upload.render({
        elem: '#itemMainImage'
        ,url:'/uploadMainItemImage'
        ,size:10485760 //10M
        ,accept:'images'
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            $("#demo1").empty();
            obj.preview(function(index, file, result){
                $('#demo1').append('<img width="40" height="40" src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img"><a>&nbsp;&nbsp;&nbsp;</a>')
            });
        }
        ,done:function (res) {
            let data = res.data;
            let mainImage = $("#mainImage");
            if (mainImage.val() == ""){
                mainImage.val(data)
            }
        }
    });

    upload.render({
        elem: '#itemImages'
        , url: '/uploadItemImages'
        , size: 10485760 //10M
        , accept: 'images'
        , multiple: true
        , before: function (obj) {
            $("#demo2").empty();
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#demo2').append('<img width="40" height="40" src="' + result + '" alt="' + file.name + '" class="layui-upload-img"><a>&nbsp;&nbsp;&nbsp;</a>')
            });
        }

        ,done:function (res) {
            let data = res.data;
            let imageList = $("#imageList");
            if (imageList.val() == ""){
                imageList.val(data)
            }else {
                imageList.val(imageList.val()+','+data);
            }
        }
    });

});

function cleanerItemText() {
    $("#itemId").val("");
    $("input[name='itemName']").val("");
    $("input[name='stock']").val("");
    $("input[name='priceNormal']").val("");
    $("input[name='discount']").val("");
    $("select[name='childItemSelect']").val(11);
    $("select[name='parentItemSelect']").val(1);
    $("input[name='itemDesc']").val("");
    $("#itemDescText").val("");
    $("input[name='productPlace']").val("");
    $("input[name='footPeriod']").val("");
    $("input[name='brand']").val("");
    $("input[name='factoryName']").val("");
    $("input[name='factoryAddress']").val("");
    $("input[name='packagingMethod']").val("");
    $("input[name='weight']").val("");
    $("input[name='storageMethod']").val("");
    $("input[name='eatMethod']").val("");
}

//修改商品
function editItem(editText) {
    //商品基本属性
    let itemId = $("#itemId").val();
    let itemName = $("input[name='itemName']").val();
    let priceNormal = $("input[name='priceNormal']").val();
    let discount = $("input[name='discount']").val();
    let priceDiscount = priceNormal * (discount / 10);
    let itemDesc = $("input[name='itemDesc']").val();
    let content = editText;
    let isSpecial = $("input[name='isSpecial']").val();
    let parentId = $("select[name='parentItemSelect']").val();
    let childId = $("select[name='childItemSelect']").val();
    let itemJson = {
        "id": itemId,
        "itemName": itemName,
        "catId": childId,
        "rootCatId": parentId,
        "priceNormal": priceNormal,
        "discount": discount,
        "priceDiscount": priceDiscount,
        "itemDesc": itemDesc,
        "content":content,
        "isSpecial": isSpecial
    };

    //商品参数

    let productPlace = $("input[name='productPlace']").val();
    let footPeriod = $("input[name='footPeriod']").val();
    let brand = $("input[name='brand']").val();
    let factoryName = $("input[name='factoryName']").val();
    let factoryAddress = $("input[name='factoryAddress']").val();
    let packagingMethod = $("input[name='packagingMethod']").val();
    let weight = $("input[name='weight']").val();
    let storageMethod = $("input[name='storageMethod']").val();
    let eatMethod = $("input[name='eatMethod']").val();
    let itemParamJson = {
        "itemId":itemId,
        "productPlace": productPlace,
        "footPeriod": footPeriod,
        "brand": brand,
        "factoryName": factoryName,
        "factoryAddress": factoryAddress,
        "packagingMethod": packagingMethod,
        "weight": weight,
        "storageMethod": storageMethod,
        "eatMethod": eatMethod
    };
    let itemInfo = {"aItem": itemJson, "aItemParam": itemParamJson};

    $.ajax({
        url: "/editItem",
        method: "post",
        charset: "UTF-8",
        dataType: "json",
        cache: false,
        contentType: "application/json;charset=utf-8;",
        data: JSON.stringify(itemInfo),
        success: function (data) {
            if (data == "1") {
                alert("修改商品成功");
                cleanerItemText();

                // layer.close(layer.index);
            } else {
                alert("修改商品失败");
                cleanerItemText();
                // layer.close(layer.index);
            }
        }
    });

}


function editItemModel(data) {
    $("#itemId").val(data.id);
    $("input[name='itemName']").val(data.itemName);
    $("input[name='stock']").val(data.stock);
    $("input[name='priceNormal']").val(data.priceNormal);
    $("input[name='discount']").val(data.discount);

    $("input[name='itemDesc']").val(data.itemDesc);
    $("input[name='isSpecial']").val(data.isSpecial);
    $("#parentItemSelect").val(data.rootCatId);
    $("#childItemSelect").val(data.catId);
    $("input[name='productPlace']").val(data.productPlace);
    $("input[name='footPeriod']").val(data.footPeriod);
    $("input[name='brand']").val(data.brand);
    $("input[name='factoryName']").val(data.factoryName);
    $("input[name='factoryAddress']").val(data.factoryAddress);
    $("input[name='packagingMethod']").val(data.packagingMethod);
    $("input[name='weight']").val(data.weight);
    $("input[name='storageMethod']").val(data.storageMethod);
    $("input[name='eatMethod']").val(data.eatMethod);
    layui.use(['layer','layedit','form'], function () {
        let layer = layui.layer, $ = layui.$,layedit = layui.layedit,form=layui.form;
        layer.open({
            type: 1,
            anim: 4,
            area: ['100%', '100%'],
            title: '修改商品',
            shadeClose: false,
            content: $('#editItem'),
            success:function () {
                layedit.set({
                    uploadImage:{
                        url:'/uploadLayEditImg',
                        type:'post'
                    },
                    parseData: function (res) {
                        return {
                            "code": res.data.code == 200 ? 0 : -1,
                            "msg": "",
                            "src": res.data.src,
                            "title":res.data.title
                        }
                    }
                })
                let editIndex = layedit.build('itemDescText',{
                    tool:['strong','italic','underline','del','|'
                        ,'left','center','right','link','unlink'
                        ,'image','help'
                    ],
                    height:150
                });

                form.on('submit(createItem)',function () {
                    form.verify({
                        content: function(value) {
                            return layedit.sync(index);
                        }
                    });
                    let editText = layedit.getContent(editIndex);
                   editItem(editText);
                });
            }
        });
    });
}


function getParentItemList() {
    $.ajax({
        url: "/getParentCategory",
        method: "post",
        charset: "UTF-8",
        async: false,
        success: function (res) {
            let parentItemSelect = $("#parentItemSelect");
            parentItemSelect.empty();
            let parentItemList = res.data;
            $.each(parentItemList, function (index, value) {
                parentItemSelect.append("<option value='" + value.id + "'" + ">" + value.name + "</option>");
            });
            getChildItemList($("#parentItemSelect").val());
        }

    })
}

function getChildItemList(parentId,form) {
    $.ajax({
        url: "/getChildCategory",
        method: "post",
        charset: "UTF-8",
        data: "parentId=" + parentId,
        async: false,
        success: function (res) {
            let childItemSelect = $("#childItemSelect");
            childItemSelect.empty();
            let childItemList = res.data;
            $.each(childItemList, function (index, value) {
                childItemSelect.append("<option value='" + value.id + "'" + ">" + value.name + "</option>");
            });
            if (form != undefined){
                form.render('select');
            }

        }

    })
}

function getCategoryInfo() {
    let parentCategory;
    let childCategory;
    let p = $("#parentCategoryList");
    let c = $("#childCategoryList");
    $.ajax({
        url:"getItemCategory"
        ,method:"post"
        ,success:function (data) {

            parentCategory = "{";
            childCategory = "{";
            $.each(data.parentCategory,function (index,item) {
                parentCategory = parentCategory+'"'+item.id+'"'+':"'+item.name + '",'

            });
            parentCategory = parentCategory.replace(/(,$)/g,'')+"}"
            $.each(data.childCategory,function (index,item) {
                childCategory = childCategory+'"'+item.id+'"'+':"'+item.name + '",'
            });
            childCategory = childCategory.replace(/(,$)/g,'')+"}"


            parentCategoryJson = JSON.parse(parentCategory)
            childCategoryJson = JSON.parse(childCategory)


        }
    })
}